

function myPromiseRace(promises) {

    return new Promise((resolve, reject) => {
        if (promises === null || typeof promises[Symbol.iterator] !== 'function') {
            throw new Error("不可迭代")
        }
        if (promises.length === 0) {
            resolve([])
        }
        promises.forEach(promise => {
            Promise.resolve(promise).then(res => {
                //? 第一个调用resolve的才会改变状态，接下来的都不会进入resolve函数的处理流程了(resolve里有if判断必须pending才能进)
                resolve(res)
            },err => {
                reject(err)
            })
        })
    })

}

const promise1 = new Promise((resolve, reject) => {
    setTimeout(() => resolve('Promise 1 resolved'), 4000);
});

const promise2 = new Promise((resolve, reject) => {
    setTimeout(() => resolve('Promise 2 resolved'), 3000);
});

const promise3 = new Promise((resolve, reject) => {
    setTimeout(() => resolve('Promise 3 resolved'), 2000);
});
const promise4 = new Promise((resolve, reject) => {
    setTimeout(() => reject('Promise 4 rejected'), 1000);
});
// 就看谁最先调用then的回调函数了 也就是看谁先执行resolve/reject
myPromiseRace([promise4, promise2, promise1, promise3])
    .then(result => console.log('Race resolved with:', result), error => console.log('Race rejected with:', error))
